package com.cloudkinto.service.orderback.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.OrderBackPageDto;
import com.cloudkinto.extentity.ReplaceBackCodeSkuDto;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.DicItemRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.orderback.OrderBackService;
import com.cloudkinto.service.orderback.OrderBackSetItemService;
import com.cloudkinto.service.orderback.vo.*;
import com.cloudkinto.service.orderinput.vo.OrderInputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputDetailRes;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.ProductStockFlowingService;
import com.cloudkinto.service.stock.StockLogService;
import com.cloudkinto.service.storage.StorageService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Time;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-08-05
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class OrderBackServiceImpl extends ServiceImpl<OrderBackDao, OrderBackDo> implements OrderBackService {
    @Autowired
    private OrderBackDao dao;
    @Autowired
    private OrderBackProductDao orderBackProductDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private StockRecordDao stockRecordDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private StorageService storageService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShipPriceService mShipPriceService;
    @Autowired
    private OperateRecordService operateRecordDao;
    @Autowired
    private OrderBackDropSetDao setTagDao;
    @Autowired
    private ProductStockDao productStockDao;
    @Autowired
    private ProductStockFlowingService productStockFlowingService;
    @Autowired
    private StockLogService stockLogService;
    @Autowired
    private OrderBackSetItemService setTagItemService;
    @Autowired
    private ProductStockRackDao productStockRackDao;

    @Override
    public SingleResult addInit(Long userId, Long companyId) {
        Map<String, List> resultMap = new HashMap<>();
        List<Map> storageList = storageService.storageList();
        resultMap.put("storageList", storageList);
        resultMap.put("trackTypeList", this.getTrackTypeList());
        resultMap.put("shopList", shopService.selectShopListInit(userId, companyId));
        return SingleResult.success(resultMap);
    }

    public List<Map> getTrackTypeList() {
        List<Map> list = new ArrayList<>();
        for (StaticDict.Order_Back_Track_Type value : StaticDict.Order_Back_Track_Type.values()) {
            Map map = new HashMap();
            map.put("id", value.getValue());
            map.put("value", value.getText());
            list.add(map);
        }
        return list;
    }

    @Override
    public OrderBackAddReq add(OrderBackAddReq req, Long userId, Long companyId) {
        OrderBackDo entityDo = new OrderBackDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        entityDo.setCompanyId(companyId);
        if (StringUtils.isNotBlank(req.getTrackNumber())) {//如果有追踪号 自动审核为已审核状态
            entityDo.setStatus(DicBusinessItemConstant.orderBackCheckStatus);
            entityDo.setTrackNumber(entityDo.getTrackNumber().replaceAll("-", ""));
        } else {
            entityDo.setStatus(DicBusinessItemConstant.orderBackCreateStatus);
        }
        if (req.getShopId() == null) throw new BizException("pls.chose.shop");
        addCheck(entityDo);
        dao.insert(entityDo);
        if (StringUtils.isBlank(entityDo.getOrderOutNumber())) {
            entityDo.setOrderOutNumber(OrderCodeUtil.getBackOrderNumber(entityDo.getId()));
        }
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_CREATE_BACK, entityDo.getId(), userId, 8);
        dao.updateById(entityDo);
        for (OrderBackAddItem item : req.getItems()) {
            if (item.getCount() == null || item.getCount() == 0) {
                throw new BizExceptionI18(SysConstant.PLS_INPUT_SKU_COUNT);
            }
            OrderBackProductDo productDo = new OrderBackProductDo();
            productDo.setCount(item.getCount());
            productDo.setOrderId(entityDo.getId());
            productDo.setCreateBy(userId);
            productDo.setCreateTime(new Date());
            productDo.setProductId(item.getProductId());
            productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            orderBackProductDao.insert(productDo);
        }
        return req;
    }


    @Override
    public void processorStorage(OrderBackProcessorStorageReq req, Long userId, Long companyId) {
        OrderBackDo orderBackDo = dao.selectById(req.getId());
        if (orderBackDo == null || orderBackDo.getStatus() > DicBusinessItemConstant.orderBackInStatus) {
            throw new BizExceptionI18(SysConstant.ORDER_HAS_RESOLVED);
        }

        orderBackDo.setFileId(req.getFileId());

        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, orderBackDo.getId());
        orderBackProductDao.delete(wrapper);

        req.getItemReqs().forEach(orderBackItemReq -> {
            OrderBackProductDo orderBackProductDo = new OrderBackProductDo();
            orderBackProductDo.setCount(orderBackItemReq.getCount());
            orderBackProductDo.setOrderId(orderBackDo.getId());
            orderBackProductDo.setProductId(req.getId());
            orderBackProductDo.setCreateBy(userId);
            orderBackProductDo.setCreateTime(new Date());
            orderBackProductDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            orderBackProductDao.insert(orderBackProductDo);
        });

        if (req.getFileId() != null) {
            fileService.uploadFile(req.getFileId());
        }
    }

    @Override
    public void customerProcessing(OrderBackCustomerProcessingReq req, Long userId, Long companyId) {
        OrderBackDo orderBackDo = dao.selectById(req.getId());
        if (orderBackDo == null) {
            throw new BizExceptionI18(SysConstant.NO_ORDER_INFO);
        }
        if (orderBackDo.getStatus() > DicBusinessItemConstant.orderBackInstructions) {
            throw new BizExceptionI18(SysConstant.ORDER_HAS_RESOLVED);
        }
        if (orderBackDo.getStatus() < DicBusinessItemConstant.orderBackInStatus) {
            throw new BizExceptionI18(SysConstant.BACKORDER_NO_IN);
        }
        if (orderBackDo.getShopId() == null && (req.getOperate() == 2 || req.getOperate() == 1)) {
            throw new BizExceptionI18(SysConstant.PLS_BACKORDER_CHOOSE_SHOP);
        }
        if (StringUtils.isNotBlank(req.getTips()))
            orderBackDo.setTips((orderBackDo.getTips() == null ? "" : orderBackDo.getTips()) + "顾客备注：" + req.getTips() + "\n");
        handlerAbandon(req, userId, orderBackDo);
    }

    private void handlerWorkOrder(OrderBackCustomerProcessingReq req, Long userId, OrderBackDo orderBackDo) {
        orderBackDo.setUpdateBy(userId);
        orderBackDo.setUpdateTime(new Date());

        dao.updateById(orderBackDo);
    }

    private void handlerAbandon(OrderBackCustomerProcessingReq req, Long userId, OrderBackDo orderBackDo) {
        orderBackDo.setUpdateBy(userId);
        orderBackDo.setUpdateTime(new Date());
        orderBackDo.setIndicateTime(new Date());
        String operateStr;
        if (req.getOperate() == 1) {//上架
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackPutAway);
            orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
            operateStr = SysConstant.OPERATE_INSTORAGE_ORDER_GOOD;
            this.handlerPutaway(req, userId, orderBackDo);
        } else if (req.getOperate() == 2) {//上架
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackPutAwayBad);
            orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
            operateStr = SysConstant.OPERATE_INSTORAGE_ORDER_BAD;
            this.handlerPutaway(req, userId, orderBackDo);
        } else if (req.getOperate() == 3) {//废弃
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackAbandon);
            orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
            operateStr = SysConstant.OPERATE_INDICATION_DROP_BACK;
        } else if (req.getOperate() == 4) {//定制工单
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackWorkOrder);
            orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
            orderBackDo.setOperateFileId(req.getOperateFileId());
            orderBackDo.setPreOperateTime(req.getTime());
            operateStr = SysConstant.OPERATE_INDICATION_WORK_BACK;
        } else {
            if (orderBackDo.getDoubleCheck() == 0) {
                orderBackDo.setDoubleCheck(1);
                orderBackDo.setBackResult(0L);
                operateStr = SysConstant.OPERATE_INDICATION_DEOUBLE_CHECK_BACK;
                orderBackDo.setStatus(DicBusinessItemConstant.orderBackInstructions);
                operateRecordDao.operateAddRecord(operateStr, orderBackDo.getId(), userId, 8);
                dao.updateById(orderBackDo);
            } else {
                throw new BizExceptionI18(SysConstant.DOUBLE_CHECK_HAS_OPERATED);
            }
            return;
        }
        dao.updateById(orderBackDo);

        operateRecordDao.operateAddRecord(operateStr, orderBackDo.getId(), userId, 8);
//        operateRecord(String.format("指示%s", operateStr), orderBackDo.getId(), userId);
    }


    private void handlerPutaway(OrderBackCustomerProcessingReq req, Long userId, OrderBackDo orderBackDo) {
        if (req.getOperate() == 1) {
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackPutAway);
            orderBackDo.setOverdueDate(null);
        } else {
            orderBackDo.setBackResult(DicBusinessItemConstant.orderBackPutAwayBad);
            orderBackDo.setOverdueDate(DateUtils.passingDate(new Date(), 30));
        }
        boolean putFlag = true;
        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, req.getId());
        List<OrderBackProductDo> orderBackProductDos = orderBackProductDao.selectList(wrapper);
        for (OrderBackProductDo orderBackProductDo : orderBackProductDos) {
            if (orderBackProductDo.getProductId() == null) {
                if (req.getOperate() == 1 || req.getOperate() == 2)
                    throw new BizExceptionI18(SysConstant.PLS_EDIT_UNKNOWN_SKU);
            }
            if (orderBackProductDo.getStockRackId() == null) {
                putFlag = false;
            }
        }

//        if (!putFlag) {
//            //说明没有安排库位
//            return;
//        }
//        else {
//            //状态变成 已处理
//            orderBackDo.setStatus(DicBusinessItemConstant.orderBackFinish);
//        }
//        //去上架库存
//        orderBackProductDos.forEach(orderBackProductDo -> {
//            LambdaQueryWrapper<StockRecordDo> stockRecordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            stockRecordDoLambdaQueryWrapper.eq(StockRecordDo::getStorageId, orderBackDo.getStorageId()).eq(StockRecordDo::getShopId, orderBackDo.getShopId()).eq(StockRecordDo::getProductInfoId, orderBackProductDo.getProductId());
//
//            StockRecordDo stockRecordDo = stockRecordDao.selectOne(stockRecordDoLambdaQueryWrapper);
//            if (stockRecordDo != null) {
//                if (req.getOperate() == 1) {
//                    stockRecordDo.setCanSellCount(stockRecordDo.getCanSellCount() + orderBackProductDo.getCount());
//                } else {
//                    stockRecordDo.setCanotSellCount(stockRecordDo.getCanotSellCount() + orderBackProductDo.getCount());
//                }
//                stockRecordDo.setUpdateBy(userId);
//                stockRecordDo.setUpdateTime(new Date());
//                stockRecordDao.updateById(stockRecordDo);
//            } else {
//                stockRecordDo = new StockRecordDo();
//                if (req.getOperate() == 1) {
//                    stockRecordDo.setCanSellCount(stockRecordDo.getCanSellCount() + orderBackProductDo.getCount());
//                } else {
//                    stockRecordDo.setCanotSellCount(stockRecordDo.getCanotSellCount() + orderBackProductDo.getCount());
//                }
//                stockRecordDo.setProductInfoId(orderBackProductDo.getProductId());
//                stockRecordDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
//                stockRecordDo.setStorageId(orderBackDo.getStorageId());
//                stockRecordDo.setShopId(orderBackDo.getShopId());
//                stockRecordDo.setCompanyId(orderBackDo.getCompanyId());
//                stockRecordDao.insert(stockRecordDo);
//            }
//            ProductStockDo stockDo = new ProductStockDo();
//            stockDo.setCompanyId(orderBackDo.getCompanyId());
//            stockDo.setCreateBy(userId);
//            stockDo.setCreateTime(new Date());
//            stockDo.setProductId(orderBackProductDo.getProductId());
//            stockDo.setStorageId(orderBackDo.getStorageId());
//            if (req.getOperate() == 1) {
//                stockDo.setGoodQuantity(orderBackProductDo.getCount());
//                stockDo.setReceiveGoodQuantity(stockDo.getGoodQuantity());
//                stockDo.setBadQuantity(0);
//            } else {
//                stockDo.setGoodQuantity(0);
//                stockDo.setReceiveGoodQuantity(stockDo.getGoodQuantity());
//                stockDo.setBadQuantity(orderBackProductDo.getCount());
//            }
//            stockDo.setReceiveQuantity(stockDo.getGoodQuantity() + stockDo.getBadQuantity());
//            stockDo.setOrderId(orderBackDo.getId());
//            stockDo.setOrderType("OB");//入库单
////            stockDo.setShopId(orderInputDo.getShopId());
//            if (stockDo.getReceiveQuantity() == 0) {
//                return;
//            }
//            //单位成本 * 单位体积
//            productStockDao.insert(stockDo);
//
////                        if (rackMap.get(productId) == null || rackMap.get(productId).get(0).getList().size() == 0) {
//            //添加到库位表
//            ProductStockRackDo rackDo = new ProductStockRackDo();
//            rackDo.setGoodQuantity(stockDo.getGoodQuantity());
//            rackDo.setBadQuantity(stockDo.getBadQuantity());
//            rackDo.setStockId(stockDo.getId());
//            rackDo.setCreateTime(new Date());
//            rackDo.setRackId(orderBackProductDo.getStockRackId());
//            productStockRackDao.insert(rackDo);
//
//            productStockFlowingService.insertFlowing(StaticDict.Product_Flowing_Type.Back.getValue(), orderBackDo.getOrderOutNumber(), orderBackDo.getShopId(), orderBackProductDo.getProductId(), orderBackDo.getStorageId(),
//                    rackDo.getGoodQuantity(), rackDo.getBadQuantity(), 0, orderBackProductDo.getStockRackId(), orderBackDo.getCompanyId(), userId, "退货单:" + orderBackDo.getOrderOutNumber() + " 入库");
//            //库存日志
//            stockLogService.saveAutoSendOutLog(req.getOperate() == 1 ? 0 : 1, orderBackProductDo.getProductId(), orderBackDo.getShopId(), orderBackDo.getStorageId(), orderBackProductDo.getCount(), (req.getOperate() == 1 ? stockRecordDo.getCanSellCount() : stockRecordDo.getCanotSellCount()), orderBackDo.getCompanyId(), userId, StringUtils.isNotBlank(orderBackDo.getOrderOutNumber()) ? orderBackDo.getOrderOutNumber() : "退货:" + orderBackDo.getId());
//        });

    }

    //新增校验
    private void addCheck(OrderBackDo orderBackDo) {
        LambdaQueryWrapper<OrderBackDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackDo::getTrackNumber, orderBackDo.getTrackNumber())
                .gt(OrderBackDo::getCreateTime, TimeUtils.getCurrentDateFormat(-60));
        Integer count = dao.selectCount(wrapper);
        if (count > 0)
            throw new BizExceptionI18(SysConstant.ORDER_BACK_HAS_EXISTED);
    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OrderBackDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }


    @Override
    public int getUnDealCount(Long companyId) {
        LambdaQueryWrapper<OrderBackDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackDo::getCompanyId, companyId).eq(OrderBackDo::getStatus, DicBusinessItemConstant.orderBackInStatus);
        Integer count = dao.selectCount(wrapper);
        return count;
    }

    @Override
    public SingleResult updateInit(Long id, Long userId, Long companyId) {
        Map result = (Map) addInit(userId, companyId).getData();

        result.put("detail", detail(id));

        return SingleResult.success(result);
    }

    @Override
    public OrderBackUpdateReq update(OrderBackUpdateReq req, Long userId) {
        for (OrderBackAddItem item : req.getItems()) {
            if (item.getCount() == null || item.getCount() == 0) {
                throw new BizExceptionI18(SysConstant.PLS_INPUT_SKU_COUNT);
            }
        }
        OrderBackDo entityDo = dao.selectById(req.getId());
        if (entityDo.getStatus() > DicBusinessItemConstant.orderBackInstructions && !Objects.equals(entityDo.getCompanyId(),201L)) {
            throw new BizExceptionI18(SysConstant.ORDER_HAS_RESOLVED);
        }

        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, req.getId());
        List<OrderBackProductDo> orderBackProductDos = orderBackProductDao.selectList(wrapper);

        for (int i = 0; i < req.getItems().size(); i++) {
            if (i < orderBackProductDos.size()) {
                //更新
                OrderBackProductDo orderBackProductDo = orderBackProductDos.get(i);
                orderBackProductDo.setProductId(req.getItems().get(i).getProductId());
                orderBackProductDo.setCount(req.getItems().get(i).getCount());
                orderBackProductDao.updateById(orderBackProductDo);
            } else {
                //插入
                OrderBackProductDo productDo = new OrderBackProductDo();
                productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                productDo.setProductId(req.getItems().get(i).getProductId());
                productDo.setCreateTime(new Date());
                productDo.setCreateBy(userId);
                productDo.setOrderId(req.getId());
                productDo.setCount(req.getItems().get(i).getCount());
                orderBackProductDao.insert(productDo);
            }
        }
        //删除多余的
        for (int i = req.getItems().size(); i < orderBackProductDos.size(); i++) {
            orderBackProductDao.deleteById(orderBackProductDos.get(i).getId());
        }

        operateRecordDao.operateAddRecord(SysConstant.OPERATE_UPDATE_BACK, entityDo.getId(), userId, 8);
        return req;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OrderBackDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }


    @Override
    public int delete(Long id, Long userId) {
        OrderBackDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.updateById(entityDo);
//        if (entityDo.getStatus()>)
        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, id);
        orderBackProductDao.delete(wrapper);

        fileService.deleteFile(entityDo.getFileId());

        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OrderBackDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }


    @Override
    public OrderBackDetailRes detail(Long id) {
        OrderBackDo entityDo = dao.selectById(id);
        OrderBackDetailRes res = new OrderBackDetailRes();
        BeanUtils.copyProperties(entityDo, res);
        res.setFileId(entityDo.getFileId());
        res.setFileUrl(fileService.getFilePath(entityDo.getFileId()));
        if (entityDo.getProductFileId() != null) {
            try {
                List<String> urlData = new ArrayList<>();
                if (entityDo.getProductFileId().contains(",")) {
                    String[] split = entityDo.getProductFileId().split(",");
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        urlData.add(fileService.getFilePath(Long.parseLong(s)));
                    }
                } else {
                    if (StringUtils.isNotBlank(entityDo.getProductFileId()))
                        urlData.add(fileService.getFilePath(Long.parseLong(entityDo.getProductFileId())));
                }
                res.setProductFileUrl(urlData);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        if (entityDo.getDoubleCheckFileId() != null) {
            try {
                List<String> urlData = new ArrayList<>();
                if (entityDo.getDoubleCheckFileId().contains(",")) {
                    String[] split = entityDo.getDoubleCheckFileId().split(",");
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        urlData.add(fileService.getFilePath(Long.parseLong(s)));
                    }
                } else {
                    urlData.add(fileService.getFilePath(Long.parseLong(entityDo.getDoubleCheckFileId())));
                }
                res.setDoubleCheckFileUrl(urlData);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        if (entityDo.getOperateFileId() != null) {
            res.setOperateFileUrl(fileService.getFilePath(entityDo.getOperateFileId()));
        }
        ShopDo shopDo = shopService.getBaseMapper().selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
        StorageDo storageDo = storageService.getBaseMapper().selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorageName(storageDo.getStorageName());
        }
        String status = dicBusinessItemService.getDicItemValue(entityDo.getStatus());
        if (StringUtils.isNotBlank(status)) {
            res.setStatus(status);
            if (entityDo.getDoubleCheck() == 1 && entityDo.getBackResult() == null && (entityDo.getStatus() == DicBusinessItemConstant.orderBackInStatus
                    || entityDo.getStatus() == DicBusinessItemConstant.orderBackInstructions)) {
                res.setStatus(status + StringsUtil.createI18Message("(二次确认)"));
            }
        }
        res.setBackResult(dicBusinessItemService.getDicItemValue(entityDo.getBackResult()));

        if (entityDo.getArrivalTime() != null) {
            res.setArriveDate(TimeUtils.formatDate(entityDo.getArrivalTime(), "MM月dd日"));
        }
        if (entityDo.getLastDate() != null) {
            res.setLastDate(TimeUtils.formatDate(entityDo.getLastDate(), "MM月dd日"));
        }
        if (entityDo.getDealDate() != null) {
            res.setDealDate(TimeUtils.formatDate(entityDo.getDealDate(), "MM月dd日"));
        }
        res.setOpenBox(entityDo.getOpenBox() == 0 ? "未开箱" : "已开箱");
        res.setCanSale(entityDo.getCanSale() == 0 ? "可贩卖" : (entityDo.getCanSale() == 1 ? "不可贩卖" : "待确认"));
        List<OrderBackDetailItem> items = new ArrayList<>();
        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, id);
        double[] sizeTemp = new double[4];
        List<OrderBackProductDo> orderBackProductDos = orderBackProductDao.selectList(wrapper);
        for (OrderBackProductDo orderBackProductDo : orderBackProductDos) {
            OrderBackDetailItem item = new OrderBackDetailItem();
            item.setCount(orderBackProductDo.getCount());
            item.setBackSkuCode(orderBackProductDo.getBackSkuCode());
            ProductInfoDo productInfoDo = productInfoDao.selectById(orderBackProductDo.getProductId());
            try {
                if (productInfoDo != null) {
                    item.setProductId(productInfoDo.getId());
                    item.setProductName(productInfoDo.getProductName());
                    item.setSku(productInfoDo.getCommoditySku());
                    sizeTemp = mShipPriceService.countSameSkuSizeNew(sizeTemp, productInfoDo, orderBackProductDo.getCount());
                } else {
                    sizeTemp = mShipPriceService.countSameSkuSizeNew(sizeTemp, orderBackProductDo.getLength(), orderBackProductDo.getWidth(), orderBackProductDo.getHeight(), orderBackProductDo.getWeight(), orderBackProductDo.getCount());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            items.add(item);
        }
        res.setPackageLength(new BigDecimal(sizeTemp[0]).setScale(2, RoundingMode.UP).doubleValue());
        res.setPackageWidth(new BigDecimal(sizeTemp[1]).setScale(2, RoundingMode.UP).doubleValue());
        res.setPackageHeight(new BigDecimal(sizeTemp[2]).setScale(2, RoundingMode.UP).doubleValue());
        res.setPackageWeight(new BigDecimal(sizeTemp[3]).setScale(2, RoundingMode.UP).doubleValue());
        res.setItems(items);
        res.setOperateResList(operateRecordDao.getOperateList(entityDo.getId(), 8));
        return res;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit(Long shopId, Long companyId, Long currentUserId) {
        Map map = new HashMap();
        map.put("shopList", shopService.selectShopListInit(currentUserId, companyId));
        List<Map> statusList = new ArrayList<>();
        List<DicItemRes> transportType = dicBusinessItemService.getDicItemList(DicBusinessConstant.orderBackStatus);
        if (!CollectionUtils.isEmpty(transportType)) {
            transportType.forEach(e -> {
                Map map1 = new HashMap();
                map1.put("id", e.getId());
                map1.put("value", e.getValue());
                statusList.add(map1);
            });
        }
        map.put("statusList", statusList);
        List<Map> resultList = new ArrayList<>();
        List<DicItemRes> resultType = dicBusinessItemService.getDicItemList(DicBusinessConstant.orderBackResult);
        if (!CollectionUtils.isEmpty(resultType)) {
            resultType.forEach(e -> {
                Map map1 = new HashMap();
                map1.put("id", e.getId());
                map1.put("value", e.getValue());
                resultList.add(map1);
            });
        }
        map.put("trackTypeList", this.getTrackTypeList());
        map.put("resultList", resultList);
        return SingleResult.success(map);
    }

    @Override
    public List<OrderBackPageRes> getList(Map<String, String> map) {
        if ("all".equals(map.get("status"))) {
            map.put("status", null);
        }
//        QueryWrapper<OrderBackDo> wrapper = queryBuild(map);
//        List<OrderBackDo> list = this.list(wrapper);
//        List<OrderBackPageRes> result = handlerListAfter(list);
        List<OrderBackPageDto> list = dao.listPage(map);
        List<OrderBackPageRes> result = handlerListAfterDto(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
//        QueryWrapper<OrderBackDo> wrapper = queryBuild(map);
//        IPage<OrderBackDo> page = pageInit(map);
//        page = this.page(page, wrapper);
//        List<OrderBackPageRes> resList = handlerListAfter(page.getRecords());

        IPage<OrderBackPageDto> page = pageInitDto(map);
        List<OrderBackPageDto> list = dao.listPage(page, map);
        List<OrderBackPageRes> resList = handlerListAfterDto(list);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(countStatus(map));
        return result;
    }

    private Map countStatus(Map<String, String> map) {
        List<Map> result = new ArrayList<>();
        Map mapTotal = new HashMap();
        map.put("status", "");
        List<OrderBackPageDto> list = dao.listPage(map);
        mapTotal.put("count", list.size());
        mapTotal.put("id", "");
        mapTotal.put("name", StringsUtil.createI18Message("全部"));
        result.add(mapTotal);

        Map<Long, List<OrderBackPageDto>> listMap = list.stream().collect(Collectors.groupingBy(OrderBackPageDto::getStatus));
        LambdaQueryWrapper<DicBusinessItemDo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.orderBackStatus);
        wrapper1.orderByAsc(DicBusinessItemDo::getSort);

        List<DicBusinessItemDo> itemDoList = dicBusinessItemDao.selectList(wrapper1);
        for (DicBusinessItemDo itemDo : itemDoList) {
            Map map1 = new HashMap();
            map.put("status", itemDo.getId() + "");
            map1.put("id", itemDo.getId());
            if (listMap.get(itemDo.getId()) != null) {
                map1.put("count", listMap.get(itemDo.getId()).size());
            } else {
                map1.put("count", 0);
            }
            map1.put("name", StringsUtil.createI18Message(itemDo.getDicItemValue()));
            result.add(map1);
        }

        Map map2 = new HashMap();
        map2.put("census", result);
        return map2;
    }


    private List<OrderBackPageRes> handlerListAfterDto(List<OrderBackPageDto> list) {
        List<OrderBackPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(orderBackDo -> {
                OrderBackPageRes res = new OrderBackPageRes();
                BeanUtils.copyProperties(orderBackDo, res);
                String status = dicBusinessItemService.getDicItemValue(orderBackDo.getStatus());
                if (StringUtils.isNotBlank(status)) {
                    res.setStatus(status);
                    if (orderBackDo.getDoubleCheck() == 1 && (orderBackDo.getBackResult() == null || orderBackDo.getBackResult() == 0L) && (orderBackDo.getStatus() == DicBusinessItemConstant.orderBackInStatus
                            || orderBackDo.getStatus() == DicBusinessItemConstant.orderBackInstructions)) {
                        res.setStatus(status + StringsUtil.createI18Message("(二次确认)"));
                    }
                }
                res.setBackResult(dicBusinessItemService.getDicItemValue(orderBackDo.getBackResult()));
                res.setBackResultId(orderBackDo.getBackResult());
//                if (orderBackDo.getBackResult().equals(DicBusinessItemConstant.orderBackPutAwayBad)) {
//
//                }
                List<OrderBackDetailItem> itemList = new ArrayList<>();
                //商品信息
                List<OrderBackProductDo> items = orderBackProductDao.selectList(new LambdaQueryWrapper<OrderBackProductDo>()
                        .eq(OrderBackProductDo::getOrderId, orderBackDo.getId()));
                for (OrderBackProductDo orderBackProductDo : items) {
                    OrderBackDetailItem item = new OrderBackDetailItem();
                    item.setCount(orderBackProductDo.getCount());
                    item.setBackSkuCode(orderBackProductDo.getBackSkuCode());
                    ProductInfoDo productInfoDo = productInfoDao.selectById(orderBackProductDo.getProductId());
                    if (productInfoDo != null) {
                        item.setProductId(productInfoDo.getId());
                        item.setProductName(productInfoDo.getProductName());
                        item.setSku(productInfoDo.getCommoditySku());
                    } else {
                        item.setProductName("未知商品");
                        item.setSku("未知商品");
                    }
                    itemList.add(item);
                }
                res.setList(itemList);
                result.add(res);
            });
        }
        return result;
    }


    @Override
    public SingleResult productType() {
        List<Map> productTypeList = new ArrayList<>();
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.productType);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo businessItemDo : businessItemDoList) {
                Map map = new HashMap();
                map.put("id", businessItemDo.getId());
                map.put("value", businessItemDo.getDicItemValue());
                productTypeList.add(map);
            }
        }
        return SingleResult.success(productTypeList);
    }

    //查询分页列表之后对列表数据的处理
    private List<OrderBackPageRes> handlerListAfter(List<OrderBackDo> list) {
        List<OrderBackPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(orderBackDo -> {
                OrderBackPageRes res = new OrderBackPageRes();
                BeanUtils.copyProperties(orderBackDo, res);

                ShopDo shopDo = shopService.getBaseMapper().selectById(orderBackDo.getShopId());
                if (shopDo != null) {
                    res.setShopName(shopDo.getShopName());
                } else {
                    res.setShopName(StringsUtil.createI18Message("待认领"));
                }
                StorageDo storageDo = storageService.getBaseMapper().selectById(orderBackDo.getStorageId());
                if (storageDo != null) {
                    res.setStorageName(storageDo.getStorageName());
                }
                String status = dicBusinessItemService.getDicItemValue(orderBackDo.getStatus());
                if (StringUtils.isNotBlank(status)) {
                    res.setStatus(status);
                    if (orderBackDo.getDoubleCheck() == 1 && (orderBackDo.getBackResult() == null || orderBackDo.getBackResult() == 0L) && (orderBackDo.getStatus() == DicBusinessItemConstant.orderBackInStatus
                            || orderBackDo.getStatus() == DicBusinessItemConstant.orderBackInstructions)) {
                        res.setStatus(status + StringsUtil.createI18Message("(二次确认)"));
                    }
                }

                res.setBackResult(dicBusinessItemService.getDicItemValue(orderBackDo.getBackResult()));

                res.setBackResultId(orderBackDo.getBackResult());
                if (orderBackDo.getArrivalTime() != null) {
                    res.setArriveDate(TimeUtils.formatDate(orderBackDo.getArrivalTime(), "MM月dd日"));
                } else {
                    res.setArriveDate(TimeUtils.formatDate(orderBackDo.getCreateTime(), "MM月dd日"));
                }
                if (orderBackDo.getLastDate() != null) {
                    res.setLastDate(TimeUtils.formatDate(orderBackDo.getLastDate(), "MM月dd日"));
                }
                if (orderBackDo.getDealDate() != null) {
                    res.setDealDate(TimeUtils.formatDate(orderBackDo.getDealDate(), "MM月dd日"));
                }
                res.setOpenBox(orderBackDo.getOpenBox() == 0 ? "未开箱" : "已开箱");
                res.setCanSale(orderBackDo.getCanSale() == 0 ? "可贩卖" : (orderBackDo.getCanSale() == 1 ? "不可贩卖" : "待确认"));
                result.add(res);
            });
        }
        return result;
    }

    private IPage<OrderBackPageDto> pageInitDto(Map<String, String> map) {
        IPage<OrderBackPageDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private IPage<OrderBackDo> pageInit(Map<String, String> map) {
        IPage<OrderBackDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OrderBackDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderBackDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_out_number", map.get("keyword")).or();
            wrapper.like("contact_name", map.get("keyword")).or();
            wrapper.like("track_number", map.get("keyword"));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.and(new Consumer<QueryWrapper<OrderBackDo>>() {
                @Override
                public void accept(QueryWrapper<OrderBackDo> orderBackDoQueryWrapper) {
                    orderBackDoQueryWrapper.eq("shop_id", map.get("shopId")).or()
                            .isNull("shop_id");
                }
            });
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("result"))) {
            wrapper.eq("back_result", map.get("result"));
        }
        if ("1".equals(map.get("dateType"))) {
            if (StringUtils.isNotBlank(map.get("sDate"))) {
                wrapper.ge("arrival_time", map.get("sDate"));
            }
            if (StringUtils.isNotBlank(map.get("eDate"))) {
                wrapper.le("arrival_time", map.get("eDate"));
            }
        } else {
            if (StringUtils.isNotBlank(map.get("sDate"))) {
                wrapper.ge("create_time", map.get("sDate"));
            }
            if (StringUtils.isNotBlank(map.get("eDate"))) {
                wrapper.le("create_time", map.get("eDate"));
            }
        }
        if (StringUtils.isNotBlank(map.get("unclaimed")) && "1".equals(map.get("unclaimed"))) {
            wrapper.isNull("company_id");
        } else {
            if (StringUtils.isNotBlank(map.get("companyId"))) {
                wrapper.and(orderBackDoQueryWrapper ->
                        orderBackDoQueryWrapper.eq("company_id", map.get("companyId")));
            }
        }
        return wrapper.orderByDesc("case WHEN `status` != 47 THEN 0 ELSE null end, id");
    }

    @Override
    public Long openApiAdd(OrderBackOpenApiAddReq req, Long userId, Long companyId) {
        OrderBackDo entityDo = new OrderBackDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        entityDo.setCompanyId(companyId);
        if (StringUtils.isNotBlank(req.getTrackNumber())) {//如果有追踪号 自动审核为已审核状态
            entityDo.setStatus(DicBusinessItemConstant.orderBackCheckStatus);
        } else {
            entityDo.setStatus(DicBusinessItemConstant.orderBackCreateStatus);
        }
        dao.insert(entityDo);
        if (StringUtils.isBlank(entityDo.getOrderOutNumber())) {
            entityDo.setOrderOutNumber(OrderCodeUtil.getBackOrderNumber(entityDo.getId()));
        }
        dao.updateById(entityDo);
        for (OrderBackAddItem item : req.getItems()) {
            OrderBackProductDo productDo = new OrderBackProductDo();
            productDo.setCount(item.getCount());
            productDo.setOrderId(entityDo.getId());
            productDo.setCreateBy(userId);
            productDo.setCreateTime(new Date());
            productDo.setProductId(item.getProductId());
            productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            orderBackProductDao.insert(productDo);
        }
        return entityDo.getId();
    }

    @Override
    public Long openApiUpdate(OrderBackOpenApiUpdateReq req, Long userId) {
        OrderBackDo entityDo = dao.selectById(req.getId());

        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);


        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, req.getId());
        orderBackProductDao.delete(wrapper);

        req.getItems().forEach(orderBackAddItem -> {
            OrderBackProductDo productDo = new OrderBackProductDo();
            productDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
            productDo.setProductId(orderBackAddItem.getProductId());
            productDo.setCreateTime(new Date());
            productDo.setCreateBy(userId);
            productDo.setOrderId(req.getId());
            productDo.setCount(orderBackAddItem.getCount());
            orderBackProductDao.insert(productDo);
        });
        return req.getId();
    }

    @Override
    public boolean openApiDelete(Long id, Long userId) {
        OrderBackDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.updateById(entityDo);

        LambdaQueryWrapper<OrderBackProductDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackProductDo::getOrderId, id);
        orderBackProductDao.delete(wrapper);

        fileService.deleteFile(entityDo.getFileId());

        return dao.deleteById(id) > 0;
    }

    @Override
    public void openApiCustomerProcessing(OrderBackOpenApiCustomerProcessingReq req, Long userId, Long companyId) {
        OrderBackDo orderBackDo = dao.selectById(req.getId());
        if (orderBackDo == null || orderBackDo.getStatus() > DicBusinessItemConstant.orderBackInstructions) {
            throw new BizExceptionI18(SysConstant.ORDER_HAS_RESOLVED);

        }
        orderBackDo.setTips(req.getTips());
        handlerAbandon(req, userId, orderBackDo);
    }

    /**
     * 认领接口
     *
     * @param id
     * @param companyId
     */
    @Override
    public void unclaimed(Long id, Long companyId) {
        OrderBackDo et = dao.selectById(id);
        if (et == null) {
            throw new BizExceptionI18(SysConstant.NO_ORDER_INFO);
        }
        if (et.getCompanyId() != null) {
            throw new BizExceptionI18(SysConstant.ORDER_HAS_CLAIM);
        }
        et.setCompanyId(companyId);
        dao.updateById(et);
    }


    @Override
    public List<OrderBackDo> getUnDealList(String companyId) {
        LambdaQueryWrapper<OrderBackDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderBackDo::getStatus, DicBusinessItemConstant.orderBackInStatus);
        wrapper.eq(OrderBackDo::getCompanyId, companyId);
        wrapper.lt(OrderBackDo::getLastDate, TimeUtils.getCurrentDateFormat(3));
        return dao.selectList(wrapper);
    }

    @Override
    public OrderBackSetTagRes settagInit(Long companyId) {
        OrderBackSetTagRes res = new OrderBackSetTagRes();
        OrderBackDropSetDo orderBackDropSetDo = setTagDao.selectOne(
                new LambdaQueryWrapper<OrderBackDropSetDo>()
                        .eq(OrderBackDropSetDo::getCompanyId, companyId)
                        .last("limit 1"));
        List<OrderBackSetItemDo> orderBackPutSetItemDos = new ArrayList<>();
        List<OrderBackSetItemDo> orderBackDropSetItemDos = new ArrayList<>();
        if (orderBackDropSetDo != null) {
            res.setFlag(orderBackDropSetDo.getActiveFlag());
            res.setTips(orderBackDropSetDo.getTips());

            orderBackPutSetItemDos = setTagItemService.getBaseMapper().selectList(new LambdaQueryWrapper<OrderBackSetItemDo>()
                    .eq(OrderBackSetItemDo::getSetId, orderBackDropSetDo.getId())
                    .eq(OrderBackSetItemDo::getType, 1));
            orderBackDropSetItemDos = setTagItemService.getBaseMapper().selectList(new LambdaQueryWrapper<OrderBackSetItemDo>()
                    .eq(OrderBackSetItemDo::getSetId, orderBackDropSetDo.getId())
                    .eq(OrderBackSetItemDo::getType, 2));
        }
        List<DicItemRes> putItemSetList = dicBusinessItemService.getDicItemList(DicBusinessConstant.orderBackPutTagSet);
        res.setPutItems(buildTagItemInit(putItemSetList, orderBackPutSetItemDos));
        List<DicItemRes> dropItemSetList = (dicBusinessItemService.getDicItemList(DicBusinessConstant.orderBackDropTagSet));
        res.setDropItems(buildTagItemInit(dropItemSetList, orderBackDropSetItemDos));
        return res;
    }

    private List<OrderBackSetTagItemRes> buildTagItemInit(List<DicItemRes> putItemSetList, List<OrderBackSetItemDo> orderBackPutSetItemDos) {
        List<OrderBackSetTagItemRes> itemResList = new ArrayList<>();
        for (DicItemRes dicItemRes : putItemSetList) {
            OrderBackSetTagItemRes itemRes = new OrderBackSetTagItemRes(dicItemRes.getId(), dicItemRes.getValue(), false);
            if (orderBackPutSetItemDos == null || orderBackPutSetItemDos.size() < 1) {

            } else {
                for (OrderBackSetItemDo orderBackPutSetItemDo : orderBackPutSetItemDos) {
                    if (dicItemRes.getId().intValue() == orderBackPutSetItemDo.getValueId().intValue()) {
                        itemRes.setChecked(true);
                    } else {

                    }
                }
            }
            itemResList.add(itemRes);
        }
        return itemResList;
    }

    @Override
    public void settag(OrderBackSetTag tag, Long userId, Long companyId) {
        OrderBackDropSetDo orderBackDropSetDo = setTagDao.selectOne(
                new LambdaQueryWrapper<OrderBackDropSetDo>()
                        .eq(OrderBackDropSetDo::getCompanyId, companyId)
                        .last("limit 1"));
        if (orderBackDropSetDo == null) {
            orderBackDropSetDo = new OrderBackDropSetDo();
            orderBackDropSetDo.setCreateBy(userId);
            orderBackDropSetDo.setCreateTime(new Date());
        }
        orderBackDropSetDo.setTips(tag.getTips());
        orderBackDropSetDo.setActiveFlag(tag.getFlag());
        orderBackDropSetDo.setCompanyId(companyId);
        orderBackDropSetDo.setUpdateBy(userId);
        orderBackDropSetDo.setUpdateTime(new Date());
        if (orderBackDropSetDo.getId() == null || orderBackDropSetDo.getId() == 0) {
            setTagDao.insert(orderBackDropSetDo);
        } else {
            setTagDao.updateById(orderBackDropSetDo);
        }
        setTagItemService.getBaseMapper().delete(new LambdaQueryWrapper<OrderBackSetItemDo>()
                .eq(OrderBackSetItemDo::getSetId, orderBackDropSetDo.getId())
                .eq(OrderBackSetItemDo::getType, 1));
        if (tag.getPutIds() != null && tag.getPutIds().size() > 0) {
            setTagItemService.saveBatch(buidlTagItem(1, orderBackDropSetDo.getId(), tag.getPutIds()));
        }

        setTagItemService.getBaseMapper().delete(new LambdaQueryWrapper<OrderBackSetItemDo>()
                .eq(OrderBackSetItemDo::getSetId, orderBackDropSetDo.getId())
                .eq(OrderBackSetItemDo::getType, 2));
        if (tag.getPutIds() != null && tag.getPutIds().size() > 0) {
            setTagItemService.saveBatch(buidlTagItem(2, orderBackDropSetDo.getId(), tag.getDropIds()));
        }
    }

    private List<OrderBackSetItemDo> buidlTagItem(int type, Long tagId, List<Long> putIds) {
        return putIds.stream().map(id -> {
            OrderBackSetItemDo setItemDo = new OrderBackSetItemDo(tagId, type, id);
            return setItemDo;
        }).collect(Collectors.toList());
    }


    @Override
    public List<ErrorMsg> importFileForBack(MultipartFile file, Long userId, Long companyId) {
        if (companyId == null) {
            throw new BizException(SysConstant.No_Company_Info);
        }
        List<OrderBackImportVo> excelImportList = new ArrayList<>();
        if (StringUtils.isEmpty(file.getName())) {
            throw new BizException(SysConstant.File_Name_Null);
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) && !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizException(SysConstant.File_Form_Incorrect);
        }
        try {
            excelImportList = ExcelUtils.importExcel(file, 0, 1, OrderBackImportVo.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
        if (excelImportList == null) throw new BizException(SysConstant.File_Form_Incorrect);

        Map<String, Long> storageMap = new HashMap<>();
        Map<String, Long> shopMap = new HashMap<>();

        List<String> shopNameList = shopService.list(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getCompanyId, companyId)).stream().map(ShopDo::getShopName).collect(Collectors.toList());
        List<String> storageNameList = storageService.list().stream().map(StorageDo::getStorageName).collect(Collectors.toList());
        List<ErrorMsg> errorMsgs = new ArrayList<>();
        for (int i = 0; i < excelImportList.size(); i++) {
            OrderBackImportVo importVo = excelImportList.get(i);
            //店铺
            if (importVo.getShopName() == null || !shopNameList.contains(importVo.getShopName().trim())) {
                errorMsgs.add(new ErrorMsg(i + 2, "店铺：" + importVo.getShopName() + "不存在"));
                continue;
            }
            //仓库
            if (importVo.getStorageName() == null || !storageNameList.contains(importVo.getStorageName().trim())) {
                errorMsgs.add(new ErrorMsg(i + 2, "仓库：" + importVo.getShopName() + "不存在"));
                continue;
            }
            //快递公司
            if (importVo.getTrackName() == null || StaticDict.Order_Back_Track_Type.getValueByText(importVo.getTrackName().trim()) == null) {
                errorMsgs.add(new ErrorMsg(i + 2, "快递公司：" + importVo.getShopName() + "不存在"));
                continue;
            }

            //商品
            List<OrderBackAddItem> list = new ArrayList<>();
            if (StringUtils.isNotBlank(importVo.getSku1())) {
                int quantity = importVo.getCount1() == 0 ? 1 : importVo.getCount1();
                if ("未知商品".equals(importVo.getSku1())) {
                    list.add(new OrderBackAddItem(null, quantity));
                } else {
                    Long productId = productInfoService.getProductId(importVo.getSku1(), companyId);
                    if (productId == null) {
                        errorMsgs.add(new ErrorMsg(i + 2, "sku：" + importVo.getSku1() + "不存在"));
                        continue;
                    }
                    list.add(new OrderBackAddItem(productId, quantity));
                }
            }


            if (StringUtils.isNotBlank(importVo.getSku2())) {
                int quantity = importVo.getCount2() == 0 ? 1 : importVo.getCount2();
                if ("未知商品".equals(importVo.getSku2())) {
                    list.add(new OrderBackAddItem(null, quantity));
                } else {
                    Long productId = productInfoService.getProductId(importVo.getSku2(), companyId);
                    if (productId == null) {
                        errorMsgs.add(new ErrorMsg(i + 2, "sku：" + importVo.getSku2() + "不存在"));
                        continue;
                    }
                    list.add(new OrderBackAddItem(productId, quantity));
                }
            }

            if (StringUtils.isNotBlank(importVo.getSku3())) {
                int quantity = importVo.getCount3() == 0 ? 1 : importVo.getCount3();
                if ("未知商品".equals(importVo.getSku3())) {
                    list.add(new OrderBackAddItem(null, quantity));
                } else {
                    Long productId = productInfoService.getProductId(importVo.getSku3(), companyId);
                    if (productId == null) {
                        errorMsgs.add(new ErrorMsg(i + 2, "sku：" + importVo.getSku3() + "不存在"));
                        continue;
                    }
                    list.add(new OrderBackAddItem(productId, quantity));
                }
            }

            if (StringUtils.isNotBlank(importVo.getSku4())) {
                int quantity = importVo.getCount4() == 0 ? 1 : importVo.getCount4();
                if ("未知商品".equals(importVo.getSku4())) {
                    list.add(new OrderBackAddItem(null, quantity));
                } else {
                    Long productId = productInfoService.getProductId(importVo.getSku4(), companyId);
                    if (productId == null) {
                        errorMsgs.add(new ErrorMsg(i + 2, "sku：" + importVo.getSku4() + "不存在"));
                        continue;
                    }
                    list.add(new OrderBackAddItem(productId, quantity));
                }
            }

            if (list.size() == 0) {
                errorMsgs.add(new ErrorMsg(i + 2, "请选择商品"));
                continue;
            }

            OrderBackAddReq addReq = new OrderBackAddReq();
            BeanUtils.copyProperties(importVo, addReq);

            if (shopMap.get(importVo.getShopName().trim()) == null) {
                ShopDo shopDo = shopService.getBaseMapper().selectOne(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getShopName, importVo.getShopName().trim()).last(" limit 1"));
                if (shopDo != null) {
                    shopMap.put(shopDo.getShopName(), shopDo.getId());
                }
            }
            addReq.setShopId(shopMap.get(importVo.getShopName().trim()));

            if (storageMap.get(importVo.getStorageName().trim()) == null) {
                StorageDo storageDo = storageService.getBaseMapper().selectOne(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getStorageName, importVo.getStorageName().trim()).last(" limit 1"));
                if (storageDo != null) {
                    storageMap.put(storageDo.getStorageName(), storageDo.getId());
                }
            }
            addReq.setStorageId(storageMap.get(importVo.getStorageName().trim()));

            addReq.setTrackId(StaticDict.Order_Back_Track_Type.getValueByText(importVo.getTrackName().trim()));

            addReq.setItems(list);

            try {
                this.add(addReq, userId, companyId);
            } catch (Exception e) {
                e.printStackTrace();
                errorMsgs.add(new ErrorMsg(i + 2, "添加失败"));
            }
        }
        return errorMsgs;
    }


    @Override
    public void downErrorMsgList(List<ErrorMsg> msgList, HttpServletResponse response) {
        List<OrderBackErrorExportVo> list = new ArrayList<>();
        for (ErrorMsg s : msgList) {
            OrderBackErrorExportVo exportVo = new OrderBackErrorExportVo();
            exportVo.setMsg("第" + s.getI() + "行,错误信息：" + s.getMsg());
            list.add(exportVo);
        }
        try {
            ExcelUtils.exportExcel(list, OrderBackErrorExportVo.class, "退货单导入错误信息" + DateUtils.dateFormatToString(new Date(), "yyyy-MM-ddHHmmss"), new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportBackOrder(Map<String, String> map, HttpServletResponse response) {
        List<OrderBackDetailExportVo> list = new ArrayList<>();
        List<OrderBackPageRes> list1 = getList(map);
        for (OrderBackPageRes orderBackPageRes : list1) {
            List<OrderBackProductDo> orderBackProductDos = orderBackProductDao.selectList(new LambdaQueryWrapper<OrderBackProductDo>().eq(OrderBackProductDo::getOrderId, orderBackPageRes.getId()));
            if (orderBackProductDos == null) continue;
            List<OrderBackDetailItemExportVo> itemExportVos = new ArrayList<>();
            for (OrderBackProductDo orderBackProductDo : orderBackProductDos) {
                OrderBackDetailItemExportVo itemExportVo = new OrderBackDetailItemExportVo();
                if (orderBackProductDo.getProductId() != null) {
                    ProductInfoDo productInfoDo1 = productInfoDao.selectById(orderBackProductDo.getProductId());
                    if (productInfoDo1 != null) {

                        itemExportVo.setSku(productInfoDo1.getCommoditySku());
                        itemExportVo.setProductName(productInfoDo1.getProductName());
                        orderBackProductDo.setLength((double) productInfoDo1.getLength());
                        orderBackProductDo.setWidth((double) productInfoDo1.getWidth());
                        orderBackProductDo.setHeight((double) productInfoDo1.getHeight());
                    } else {
                        itemExportVo.setSku("-");
                        itemExportVo.setProductName("未知商品");
                    }
                } else {
                    itemExportVo.setSku("-");
                    itemExportVo.setProductName("未知商品");
                }
                itemExportVo.setBackCode(orderBackProductDo.getBackSkuCode());
                itemExportVo.setCount(orderBackProductDo.getCount());
                itemExportVo.setLength(orderBackProductDo.getLength());
                itemExportVo.setWidth(orderBackProductDo.getWidth());
                itemExportVo.setHeight(orderBackProductDo.getHeight());
                itemExportVos.add(itemExportVo);
            }
            OrderBackDetailExportVo exportVo = BeanConvert.INSTANCE.backPage2export(orderBackPageRes);
            exportVo.setItemExportVosList(itemExportVos);
            list.add(exportVo);
        }
        try {
            ExcelUtils.exportExcel(list, OrderBackDetailExportVo.class, "退货单" + DateUtils.dateFormatToString(new Date(), "yyyy-MM-ddHHmmss"), new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public double getBackStorageFee(float size, int count, int day) {
        return day * count * (size < 100 ? 10 : 30);
    }


    //获取该公司下所有的退货码

    @Override
    public List<ReplaceBackCodeSkuDto> getBackCode(Long companyId) {
        return dao.getBackCodeForReplace(companyId);
    }


    @Override
    public void applyExtension(Long id, Long userId) {
        OrderBackDo et = dao.selectById(id);
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        if (!DicBusinessItemConstant.orderBackFinish2.equals(et.getStatus()) || !DicBusinessItemConstant.orderBackPutAwayBad.equals(et.getBackResult())) {
            throw new BizExceptionI18(SysConstant.Back_Only_Finish);
        }
        et.setApplyExtension(1);
        dao.updateById(et);
        operateRecordDao.operateAddRecord(SysConstant.OrderBack_ApplyExtension, id, userId, 8);
    }
}
